package com.fulu.javabase.juc.lock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReentrantReadWriteLockTest {

    ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
    ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();

    public static void main(String[] args) throws InterruptedException {

        ReentrantReadWriteLockTest rrwt = new ReentrantReadWriteLockTest();
        new Thread(() -> rrwt.get("aaa")).start();
        new Thread(() -> rrwt.get("aaa")).start();
        new Thread(() -> rrwt.set("aaa", "bbb")).start();
        Thread.sleep(3000);
        new Thread(() -> rrwt.set("aaa", "ccc")).start();
    }

    Map<String, String> map = new HashMap<>();
    public void set(String k, String v){
        System.out.println("准备抢写锁");
        writeLock.lock();
        System.out.println("获得写锁，其他线程阻塞2秒：" + k);
        map.put(k, v);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        writeLock.unlock();
    }

    public String get(String k) {
        int i= 0;
        while (true) {
            i++;
            readLock.lock();
            System.out.println(Thread.currentThread().getName() + "获得读锁：" + map.get(k));
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            readLock.unlock();
            if(i > 20){
                break;
            }
        }
        return map.get(k);
    }
}
